<%@page import="domain.Person"%>
<%@page import="domain.Mission"%>
<%@page import="util.DateUtil"%>
<%@page import="domain.ScheduleStatus"%>
<%@page import="domain.Schedule"%>
<%@page import="java.util.List"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html> 
<html > 
<head>
	<jsp:include page="./header.jsp" />
	
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<%
	List<Schedule> schedules = (List<Schedule>) request.getAttribute("schedules");
	List<Person> drivers = (List<Person>) request.getAttribute("drivers");
	String message = (String) request.getAttribute("message");
	%>
	<title>Intelligent Route System</title>
	<!--  script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;key=ABQIAAAAwYiir9brQH570zK6R4n_gxSViLtmlsKwCN2_V3KmGYK2miLncBSFf_4CdQkwqxAkaqbQfbaWNTqk0g" type="text/javascript"></script-->
	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAvygGeDLnH_oMEXYhZUG2jBSRvfnVL9Z7D89GKRL1uQiEuOhTJxTYb5idNXuzfbvu5EJcVlEbesMtmQ" type="text/javascript"></script> 
	<!-- GOOGLE MAP -->
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
	  html { height: 100% }
	  body { height: 100%; margin: 0px; padding: 0px }
	  #map_canvas { height: 100% }
	</style>
	<script type="text/javascript"
	    src="http://maps.google.com/maps/api/js?sensor=true">
	</script>
	<script type="text/javascript" src="./resources/BpTspSolver.js"></script>
	<script type="text/javascript" src="./resources/tsp.js"></script>
	
	<script type="text/javascript">
	var tsp; // The BpTspSolver object which handles the TSP computation.
	var posList ;
	var orderMission;

	function updateMission(url, id){
		document.forms["updateMission"+id].method = "post";
		document.forms["updateMission"+id].action = "./"+url;
		document.forms["updateMission"+id].submit();
	}
		function initialize() {
		    
			/*var latlng = new google.maps.LatLng(13.711428,100.594103);
		    var myOptions = {
		      zoom: 8,
		      center: latlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };
		    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		    */
		    
		    //getSchedule();
			 //loadAtStart(13.711428, 100.594103, 10);
			 //getSchedule();
			 
		  }
		//window.onload = function(){ alert("tt");
		//	$('#current_date').append(print_today_eg);
		//}
		function getSchedule() {
			
			
	
			/*var gebMap = new GMap2(document.getElementById("map"));
			 gebMap.setCenter(new GLatLng(13.711428, 100.594103), 8);
			gebMap.addControl(new GLargeMapControl());
			gebMap.addControl(new GMapTypeControl());
			*/
		    tsp = new BpTspSolver(new GMap2(document.getElementById("map")),document.getElementById("my_textual_div"));
		   // var request = createXMLHttpRequest();
			//request.open('get','./AJAX?todo=getPOS&scheduleId=501',false);
			//request.send(null);
			//posList = eval("(" + request.responseText + ")");
			//alert('<posList.pos.length = '+posList.pos.length);
			for( var i=0; i<posList.pos.length; i++){
				tsp.addWaypoint(new GLatLng(posList.pos[i].lat, posList.pos[i].lng));
				
				//drawMarker(new GLatLng(posList.pos[i].lat, posList.pos[i].lng), tsp.getWaypoints().length);
			}
			tsp.setAvoidHighways(false);
			tsp.setTravelMode(G_TRAVEL_MODE_DRIVING);

			 tsp.solveRoundTrip(onSolveCallback2);
			// showMission();
		}
	

		function onSolveCallback2(myTsp) {
			  
			  orderStr = "";
			  for (var i = 0; i < tsp.getOrder().length; ++i) {
			    orderStr += tsp.getOrder()[i] + " ";
			  }
			 // document.getElementById("ordering").innerHTML = orderStr;

			}
			function moveMission(move,i){
				//alert(orderMission + " " +  i +" "+ down);
				var tmp;
				if(move=="down"){
					tmp =orderMission[i+1];
					orderMission[i+1]=orderMission[i];
					orderMission[i]=tmp;
				}else if(move=="up"){
					tmp =orderMission[i-1];
					orderMission[i-1]=orderMission[i];
					orderMission[i]=tmp;
				}
				showMissionTable(orderMission);
			}
			function saveMission(){
				var str = "";
				for(var i = 0 ;i<orderMission.length;i++){
					str += posList.pos[parseInt(orderMission[i])].id +":";
				}
				//alert(str);
				document.getElementById("missionList").value = str;
			}
			function showMissionTable(orderMission){
				var missionTableStr = "";
				for(var i = 1 ;i<orderMission.length-1;i++){
					missionTableStr += i + ". " +posList.pos[parseInt(orderMission[i])].name;
					missionTableStr += "<br>";
					if(i<=1){
						missionTableStr += "<input type='button' data-icon='arrow-u' onClick='moveMission(\"down\","+i+")' value='Move Down' />   ";
					}else if(i>=orderMission.length-2){
						missionTableStr += "<input type='button' data-icon='arrow-u' onClick='moveMission(\"up\","+i+")' value='Move Up' /> ";
					}else {
						missionTableStr += "<input type='button' data-icon='arrow-u' onClick='moveMission(\"up\","+i+")' value='Move Up' /> <input type='button' data-icon='arrow-u' onClick='moveMission(\"down\","+i+")' value='Move Down' /> ";	
					}
					
					missionTableStr += "<br><hr>";
				}
				//missionTableStr += "</ul>";
				//alert('missionTableStr = '+missionTableStr)
				var missionView = document.getElementById("missionTable2");
				missionView.innerHTML = missionTableStr;
				saveMission();
			}
			function showMission(bestPath){
				orderMission = bestPath.toString().split(",");
				//alert('orderMission = '+ bestPath);
				var missionTableStr = "";//"<ul data-role='listview' data-inset='true' >";
				//alert('orderMission.lenght = '+orderMission);
				//alert('orderMission.lenght = '+orderMission.length);
				showMissionTable(orderMission);
			}

	</script>
</head>
<body onload="initialize()" >
	<div data-role="page" data-theme="a">

	<div data-role="header" data-backbtn="true">
		<!--  a data-rel="back">Back</a-->
		<h1>Manage Schedule</h1>
	</div><!-- /header -->

	<div data-role="content">
	<div id="current_date" style="text-align: right;"></div>	
		<div align="center" id="map_canvas"></div>
		
		<div id="map" style="width: 0px; height: 0px; display:none;" ></div>
		<div id="my_textual_div" style="display:none"></div>
		
		<div id="ordering2" style="display:none"></div>
		
		
		<% 
				if(schedules!=null){
			%>
			<ul data-role="listview" data-inset="true" data-theme="a">
			<%
				for(int i=0; i<schedules.size(); i++){
					Schedule schedule = schedules.get(i);
			%>
					<li>
						<a href="#missions<%= schedule.getId()%>" data-transition="slide">
							<%=schedule.getRoute()%> - <%= DateUtil.getDDMMYYYYFromDate(schedule.getDate(), 0) %>
							(<%=schedule.getStatus().equals(ScheduleStatus.completed)? schedule.getStatus(): schedule.getNoOfCompletedMissions()+"/"+schedule.getNoOfAllMissions()%>)
						</a>
					</li>
				<%} %>
			</ul>
			<%}else{ %>
				<script>
					alert("There is no any schedule!!");
				</script>
			<%} %>
			</div><!-- /content -->

	<div data-role="footer" class="ui-bar">
			<h4></h4>
	</div><!-- /footer -->
	</div><!-- /page -->
	
	<!-- Mission Pages -->
		<% 
			if(schedules!=null){
		%>
		<%
			for(int i=0; i<schedules.size(); i++){
				Schedule schedule = schedules.get(i);
				List<Mission> missions = schedule.getMissions();
		%>
				<div data-role="page" id="missions<%=schedule.getId()%>" data-theme="a">
			
				<div data-role="header">
					<h1><%=schedule.getRoute()%> - <%= DateUtil.getDDMMYYYYFromDate(schedule.getDate(), 0) %></h1>
				</div><!-- /header -->
			
				<div data-role="content">
					<ul data-role="listview" data-inset="true" >
						<script type="text/javascript">
							var request = createXMLHttpRequest();
							request.open('get','./AJAX?todo=getUnPrioritizePOS&scheduleId=<%=schedule.getId()%>',false);
							request.send(null);
							posList = eval("(" + request.responseText + ")");
							//alert('posList = '+posList);
							getSchedule();
						</script>
						<li id="missionTable2">
							
						</li>
					</ul>		
					
				<form id="updateMission<%=schedule.getId() %>">
				<div data-role="fieldcontain">
				<label for="select-choice-1" class="select">Choose Driver:</label>
						<select name="select-driver" id="select-choice-1">
							<%
								for(Person p: drivers){
							%>
							<option value=<%=p.getId()%> ><%=p.getFullName() %></option>
							
							<%} %>
						</select>
				</div>	
				
							<input type="hidden" value="<%=schedule.getId() %>" name="scheduleId" id="scheduleId"/>
							<input type="hidden" value="" name="missionList" id="missionList" />
						</form>
						<br/>
							<div data-role="button" data-theme="a" onclick="updateMission('ManageSchedule', <%=schedule.getId() %>)">Update Schedule</div>
				
				</div><!-- /content -->
			
				<div data-role="footer">
					<h4></h4>
				</div><!-- /footer -->
				</div><!-- /page -->
			<%} %>
		<% } %>
</body>
</html>